package com.wewins.fota.util;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

import static org.springframework.util.StreamUtils.BUFFER_SIZE;

public class FileUtil {
    private static Logger logger = Logger.getLogger(FileUtil.class.getName());

    public static void createFile(File file) throws IOException {
        File parentFile = file.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        if (!file.exists()) {
            file.createNewFile();
        }
    }

    public static void createFile(String filePath) throws IOException {
        createFile(new File(filePath));
    }

    public static void load(HttpServletResponse response, File file) throws IOException {
        FileInputStream in = null;
        OutputStream os = null;
        try {
            in = new FileInputStream(file);
            os = response.getOutputStream();
            int len;
            byte[] buf = new byte[BUFFER_SIZE];
            while ((len = in.read(buf)) > 0) {
                os.write(buf, 0, len);
            }
        } finally {
            close(os);
            close(in);
        }
    }

    public static void close(Closeable c) {
        if (c != null) {
            try {
                c.close();
            } catch (IOException e) {
                logger.log(Level.WARNING, "may be failed to close closeable! e:", e);
            }
        }
    }
}
